<template>
  <div>
    <div style="margin-bottom: 10px; font-size: 14px; font-weight: 250; margin-left: 10px">
      <el-icon><Memo /></el-icon>
      课程管理
    </div>
    <el-card style>
      <div style="display: flex">
        <el-button type="primary" size="large" @click="addCourse">创建课程</el-button>
        <el-input placeholder="请输入课程名称" v-model="data.courseName" style="width: 300px; margin-left: 300px;"  prefix-icon="Search"/>
        <el-input placeholder="请输入教师姓名" v-model="data.teacherName" style="width: 300px; margin: 0px 20px 0px 20px" prefix-icon="Search"/>
        <el-input placeholder="请输入学院名称" v-model="data.deptName" style="width: 300px; margin: 0px 20px 0px 0px" prefix-icon="Search"/>
        <el-button type="primary" size="large" @click="load">搜索</el-button>
      </div>
      <el-table :data="data.tableData" stripe style="width: 100%">
        <el-table-column prop="id" label="课程ID" />
        <el-table-column prop="name" label="课程名" />
        <el-table-column prop="teacherName" label="教师" />
        <el-table-column prop="deptName" label="所属学院" />
        <el-table-column prop="grade" label="年级" />
        <el-table-column prop="credit" label="学分" />
        <el-table-column label="上课时间">
          <template #default="scope">
            {{ formatTimeDisplay(scope.row.time) }}
          </template>
        </el-table-column>
        <el-table-column prop="selectCount" label="已选人数" />
        <el-table-column prop="maxSize" label="最大容量" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button @click="updateCourse(scope.row)" type="primary" icon="Edit" circle />
            <el-button @click="handleDel(scope.row.id)" type="danger" icon="Delete" circle />
          </template>
        </el-table-column>
      </el-table>
      <div style="display: flex; justify-content: center; margin-top: 10px">
        <el-pagination layout="prev, pager, next" :total="data.tableData.length" :page-size="10" />
      </div>
    </el-card>
    <el-dialog v-model="data.dialogFormVisible" title="编辑" width="500">
      <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="80px" style="padding: 20px">
        <el-form-item label="课程名" prop="name">
          <el-input size="large" v-model="data.form.name" placeholder="请输入课程名称"></el-input>
        </el-form-item>
        <el-form-item label="授课教师" prop="teacher">
          <el-select v-model="data.form.teacherId">
            <el-option
                v-for="(item, index) in data.teachers"
                :key="index"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年级">
          <el-date-picker type="year" v-model="data.form.grade" value-format="YYYY" />
        </el-form-item>
        <el-form-item label="上课时间" prop="time">
          <div style="display: flex; align-items: center; gap: 10px">
            <!-- 星期选择 -->
            <el-select v-model="data.selectedWeekday" placeholder="请选择星期" style="width: 120px">
              <el-option label="星期一" value="1" />
              <el-option label="星期二" value="2" />
              <el-option label="星期三" value="3" />
              <el-option label="星期四" value="4" />
              <el-option label="星期五" value="5" />
              <el-option label="星期六" value="6" />
              <el-option label="星期日" value="7" />
            </el-select>
            <!-- 节次选择 -->
            <el-select v-model="data.selectedSection" placeholder="请选择节次" style="width: 120px">
              <el-option label="第一节" value="1" />
              <el-option label="第二节" value="2" />
              <el-option label="第三节" value="3" />
              <el-option label="第四节" value="4" />
              <el-option label="第五节" value="5" />
              <el-option label="第六节" value="6" />
              <el-option label="第七节" value="7" />
              <el-option label="第八节" value="8" />
              <el-option label="第九节" value="9" />
              <el-option label="第十节" value="10" />
              <el-option label="第十一节" value="11" />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="时长(节)" prop="courseLength">
          <el-input-number
              v-model="data.courseLength"
              :min="1"
              :max="6"
              placeholder="请输入时长(节)"
          />
        </el-form-item>
        <el-form-item label="上课地点" prop="location">
          <el-input size="large" v-model="data.form.location" placeholder="请输入上课地点"></el-input>
        </el-form-item>
        <el-form-item label="学分" prop="credit">
          <el-input size="large" v-model="data.form.credit" placeholder="请输入课程学分"></el-input>
        </el-form-item>
        <el-form-item label="最大容量" prop="maxSize">
          <el-input size="large" v-model="data.form.maxSize" placeholder="请输入课程最大人数容量"></el-input>
        </el-form-item>
        <el-form-item label="考试地点" prop="examLocation">
          <el-input size="large" v-model="data.form.examLocation" placeholder="请输入考试地点"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button @click="data.dialogFormVisible = false" size="large">取消</el-button>
          <el-button type="primary" @click="handleSave" size="large">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>

import {reactive, ref, watch} from "vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {formatCourseTime, parseTimeString} from "@/utils/timeFormatter";

const formRef = ref()

const data = reactive({
  tableData: [],
  courseName: "",
  teacherName: "",
  deptName: "",
  dialogFormVisible: false,
  teachers: [],
  selectedWeekday: '',
  selectedSection: '',
  courseLength: '',
  form: {
    time: '',
  },
  rules: {
    name: {
      required: true,
      message: "请输入课程名称",
      trigger: "blur"
    },
    location: {
      required: true,
      message: "请输入上课地点",
      trigger: "blur"
    },
    credit: {
      required: true,
      message: "请输入课程学分",
      trigger: "blur"
    },
    maxSize: {
      required: true,
      message: "请输入课程最大人数容量",
      trigger: "blur"
    },
    examLocation: {
      required: true,
      message: "请输入考试地点",
      trigger: "blur"
    },
  },
  isAdd: true,
})

// 监听星期和节次的变化，自动生成时间字符串
watch([() => data.selectedWeekday, () => data.selectedSection, () => data.courseLength],
    ([weekday, section, length]) => {
      if (weekday && section && length) {
        // 生成格式为 "星期-开始节次-节数" 的字符串
        data.form.time = `${weekday}-${section}-${length}`;
      }
    }
);

const load = () => {
  request.get("admin/selectAllCourse", {
    params: {
      courseName: data.courseName || '',
      teacherName: data.teacherName || '',
      deptName: data.deptName || '',
    }}).then(res => {
    data.tableData = res.data
  })
}

load()

const formatTimeDisplay = (timeStr) => {
  return formatCourseTime(timeStr);
};

const getTeachers = () => {
  request.get("admin/selectAllTeacher").then(res => {
    data.teachers = res.data
  })
}

getTeachers()

const addCourse = () => {
  data.dialogFormVisible = true;
  data.selectedWeekday = "1";
  data.selectedSection = "1";
  data.courseLength = "2";
  data.form = {
    teacherId: 1,
    grade: "2025"
  };
  data.isAdd = true
}

const handleAdd = () => {
  request.post("admin/addCourse", data.form).then(res => {
    if (res.code === "200") {
      ElMessage.success("创建成功")
      load()
      data.dialogFormVisible = false
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const updateCourse = (row) => {
  const timeInfo = parseTimeString(row.time);
  data.selectedWeekday = timeInfo.weekday;
  data.selectedSection = timeInfo.section;
  data.courseLength = timeInfo.length;
  request.get("admin/selectCourse", {params: {name: row.name}}).then(res => {
    data.form = res.data
  })
  data.dialogFormVisible = true
  data.isAdd = false
}

const handleEdit = () => {
  request.put("admin/updateCourse", data.form).then(res => {
    if (res.code === "200") {
      ElMessage.success("更新成功")
      load()
      data.dialogFormVisible = false
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const handleSave = () => {
  formRef.value.validate((valid) => {
    if(valid) {
      data.isAdd ? handleAdd() : handleEdit()
    }
  })
}

const handleDel = (id) => {
  ElMessageBox.confirm(
      '删除后无法复原，是否确定删除',
      '删除提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    request.delete("admin/deleteCourse/" + id).then(res => {
      if(res.code === "200") {
        ElMessage.success("删除成功")
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除',
    })
  })
}
</script>